<template>
<div class="service-container">
  <!-- 顶部操作栏 -->
  <el-card class="operation-bar">
    <el-space>
      <el-input v-model="newSessionId" placeholder="输入用户ID开始会话" style="width: 200px">
        <template #append>
          <el-button @click="startNewSession">发起会话</el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="showCreateGroup = true">新建群组</el-button>
      <el-tag :type="connectionStatus.type">
        <el-icon :class="connectionStatus.icon"></el-icon>
        {{ connectionStatus.text }}
      </el-tag>
    </el-space>
  </el-card>

  <el-row :gutter="20" class="main-layout">
    <!-- 左侧管理面板 -->
    <el-col :span="5">
      <el-card class="management-panel">
        <div class="panel-section">
          <h4>会话列表</h4>
          <el-scrollbar height="300px">
            <div v-for="session in sessions"
                 :key="session.id"
                 class="session-item"
                 :class="{ active: activeSession?.id === session.id }"
                 @click="selectSession(session)">
              <el-avatar :src="session.avatar" size="small" />
              <div class="session-info">
                <span>{{ session.name }}</span>
                <div class="session-meta">
                  <span class="time">{{ formatTime(session.lastTime) }}</span>
                  <el-badge :value="session.unread" />
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>

        <div class="panel-section">
          <h4>群组管理</h4>
          <el-input v-model="newMemberId" placeholder="输入用户ID">
            <template #append>
              <el-button @click="addGroupMember">添加成员</el-button>
            </template>
          </el-input>
          <el-scrollbar height="200px">
            <div v-for="group in groups"
                 :key="group.id"
                 class="group-item"
                 @click="selectGroup(group)">
              <div class="group-header">
                <el-avatar :src="group.avatar" size="small" />
                <span>{{ group.name }}</span>
                <el-tag type="info" size="small">{{ group.memberCount }}人</el-tag>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </el-card>
    </el-col>

    <!-- 右侧聊天区域 -->
    <el-col :span="19">
      <el-card class="chat-panel">
        <div v-if="activeSession" class="chat-container">
          <div class="message-history">
            <div v-for="msg in messages"
                 :key="msg.id"
                 :class="['message-bubble', msg.direction]">
              <div class="message-content">
                <div v-if="msg.type === 'text'">{{ msg.content }}</div>
                <div v-else-if="msg.type === 'image'">
                  <el-image :src="msg.content" :preview-src-list="[msg.content]" />
                </div>
                <div v-else-if="msg.type === 'file'">
                  <el-link type="primary" :href="msg.content" target="_blank">
                    <el-icon><Document /></el-icon> {{ msg.fileName }}
                  </el-link>
                </div>
                <div class="message-meta">
                  <span>{{ formatTime(msg.timestamp) }}</span>
                  <el-icon v-if="msg.read" class="read-status"><CircleCheck /></el-icon>
                </div>
              </div>
            </div>
          </div>

          <div class="message-editor">
            <el-upload :action="uploadUrl"
                       :headers="{ Authorization: `Bearer ${token}` }"
                       :show-file-list="false"
                       :on-success="handleFileUpload">
              <template #trigger>
                <el-button type="primary" circle>
                  <el-icon><Plus /></el-icon>
                </el-button>
              </template>
            </el-upload>

            <el-input v-model="inputMessage"
                      type="textarea"
                      :rows="3"
                      placeholder="输入消息..."
                      @keyup.enter="sendMessage" />

            <el-button type="success" @click="sendMessage">
              发送 <el-icon><Promotion /></el-icon>
            </el-button>
          </div>
        </div>

        <div v-else class="empty-state">
          <el-empty description="选择会话或创建新会话开始聊天" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 创建群组对话框 -->
  <el-dialog v-model="showCreateGroup" title="新建客服群组">
    <el-form :model="newGroupForm" label-width="80px">
      <el-form-item label="群组名称">
        <el-input v-model="newGroupForm.name" />
      </el-form-item>
      <el-form-item label="群组公告">
        <el-input v-model="newGroupForm.announcement" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showCreateGroup = false">取消</el-button>
      <el-button type="primary" @click="createGroup">创建</el-button>
    </template>
  </el-dialog>
</div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, CircleCheck, Plus, Promotion } from '@element-plus/icons-vue'
import SockJS from 'sockjs-client'
import { Client } from '@stomp/stompjs'

// 状态管理
const token = ref('YOUR_JWT_TOKEN')
const connection = reactive({
  client: null as Client | null,
  connected: false
})

const sessions = reactive([]) // 会话列表
const groups = reactive([])    // 群组列表
const activeSession = ref(null) // 当前激活的会话
const messages = reactive([])  // 当前会话消息

// 连接状态计算属性
const connectionStatus = computed(() => {
  return {
    connected: connection.connected,
    text: connection.connected ? '已连接' : '未连接',
    type: connection.connected ? 'success' : 'danger',
    icon: connection.connected ? 'el-icon-success' : 'el-icon-error'
  }
})

// 初始化WebSocket连接
const initWebSocket = () => {
  const socket = new SockJS('/ws-endpoint')
  connection.client = new Client({
    webSocketFactory: () => socket,
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000
  })

  connection.client.onConnect = (frame) => {
    connection.connected = true
    setupSubscriptions()
  }

  connection.client.activate()
}

// 设置消息订阅
const setupSubscriptions = () => {
  // 订阅私聊消息
  connection.client?.subscribe('/user/queue/messages', (message) => {
    handleIncomingMessage(JSON.parse(message.body))
  })

  // 订阅群组消息
  connection.client?.subscribe('/topic/groups', (message) => {
    // handleGroupMessage(JSON.parse(message.body))
  })
}

// 消息处理方法
const handleIncomingMessage = (message) => {
  // 消息处理逻辑...
}

// 其他功能方法...
</script>

<style scoped lang="scss">
.service-container {
  height: 100vh;
  padding: 20px;
  background: #f5f7fa;

  .operation-bar {
    margin-bottom: 20px;
  }

  .main-layout {
    height: calc(100vh - 100px);
  }

  .management-panel {
    height: 100%;

    .panel-section {
      margin-bottom: 20px;

      h4 {
        color: #666;
        margin: 0 0 12px 0;
      }
    }

    .session-item {
      display: flex;
      align-items: center;
      padding: 10px;
      cursor: pointer;
      transition: background 0.3s;

      &:hover {
        background: #f0f4ff;
      }

      &.active {
        background: #e8f4ff;
      }

      .session-info {
        margin-left: 10px;

        .time {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  .chat-panel {
    height: 100%;

    .chat-container {
      display: flex;
      flex-direction: column;
      height: 700px;

      .message-history {
        flex: 1;
        overflow-y: auto;
        padding: 20px;

        .message-bubble {
          margin: 10px 0;
          max-width: 70%;

          &.left {
            margin-right: auto;
          }

          &.right {
            margin-left: auto;
            background: #e1f3ff;
          }

          .message-content {
            padding: 12px;
            border-radius: 8px;
            background: #fff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
          }
        }
      }

      .message-editor {
        border-top: 1px solid #eee;
        padding: 20px;
        display: flex;
        gap: 10px;
        align-items: flex-end;

        :deep(.el-textarea__inner) {
          border: none;
          box-shadow: none;
        }
      }
    }
  }
}
</style>
